package token;

import util.MACUtils;

public class AuthToken {

    private static final long EXPIRE_INTERVAL = 10 * 60 * 1000L;

    private long createTime;
    private String token;
    private long expiredTimeInterval = EXPIRE_INTERVAL;

    public AuthToken(long createTime, String token) {
        this.createTime = createTime;
        this.token = token;
    }


    public AuthToken(long createTime, String token,long expiredTimeInterval) {
        this(createTime, token);
        this.expiredTimeInterval = expiredTimeInterval;
    }

    public static AuthToken create(String baseUrl, String appId, long createTime, String password){
        // 把 URL、AppID、密码、时间戳拼接为一个字符串；
        StringBuffer srcStr = new StringBuffer(baseUrl).append("?");
        srcStr.append("appId").append("=").append(appId);
        srcStr.append("&").append("password").append("=").append(password);
        srcStr.append("&").append("timestamp").append("=").append(createTime);

        // 对字符串通过加密算法加密生成 token；
        String token = MACUtils.generateToken(srcStr.toString(), password);
        AuthToken authToken = new AuthToken(createTime,token);

        return authToken;
    }

    public String getToken(){
        return this.token;
    }

    /**
     * 根据时间戳判断 token 是否过期失效；
      */
    public boolean isExpired() {
        return createTime + expiredTimeInterval < System.currentTimeMillis();
    }

    /**
     * 判断 token 是否匹配
     */
    public boolean match(AuthToken authToken) {
        return this.token.equals(authToken.getToken());
    }

}
